package top.lixunda.ecommerce.server.auth.feign;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import top.lixunda.commerce.common.core.config.FeignClientErrorDecoder;
import top.lixunda.commerce.common.core.entity.MessageObject;
import top.lixunda.commerce.common.core.exception.InternalApiException;
import top.lixunda.common.validate.exception.XumValidException;

import javax.servlet.http.HttpServletResponse;

/**
 * @author LiXunda
 * @version time:2019/10/29 17:55
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 除了了该异常之后，该异常会继续上传
     *
     * @param e        异常
     * @param response response
     * @return MessageObject
     */
    @ExceptionHandler(InternalApiException.class)
    public ResponseEntity<MessageObject> internalApiException(InternalApiException e, HttpServletResponse response) {
        FeignClientErrorDecoder.dealResponse(response);
        log.info("向上级传递InternalApiException异常 : " + e.toString());
        //设置状态码为默认中的状态码，只有这个状态码才会被接受为InternalApiException
        return ResponseEntity.status(InternalApiException.DEFAULT_HTTP_STATUS)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(MessageObject.newInstance().setCode(e.getMsgCode()).setMsg(e.getMsg()));
    }

    /**
     * 参数验证错误，可能是验证过程中的bug，也可能是发现了参数错误
     *
     * @param e        Exception
     * @param response response
     * @return MessageObject
     */
    @ExceptionHandler(XumValidException.class)
    public ResponseEntity<MessageObject> exception(XumValidException e, HttpServletResponse response) {
        FeignClientErrorDecoder.dealResponse(response);
        log.info("向上级传递参数验证异常 : " + e.toString());
        e.printStackTrace();
        //设置状态码为默认中的状态码，只有这个状态码才会被接受为InternalApiException
        return ResponseEntity.status(InternalApiException.DEFAULT_HTTP_STATUS)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(MessageObject.newInstance().setCode(MessageObject.CODE_ERROR_PARAMETER)
                        .setMsg(e.getMessage()));
    }

    /**
     * 未处理异常，也会像上级传递
     *
     * @param e        Exception
     * @param response response
     * @return MessageObject
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<MessageObject> exception(Exception e, HttpServletResponse response) {
        FeignClientErrorDecoder.dealResponse(response);
        log.info("向上级传递InternalApiException异常 : " + e.toString());
        e.printStackTrace();
        //设置状态码为默认中的状态码，只有这个状态码才会被接受为InternalApiException
        return ResponseEntity.status(InternalApiException.DEFAULT_HTTP_STATUS)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(MessageObject.error("未处理异常，联系管理员"));
    }

}
